//
//  MainViewController.swift
//  XFweibo
//
//  Created by DragonSL on 15/11/17.
//  Copyright © 2015年 lcl. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 添加控制器, 并不会创建 tabBar中的按钮
        // 懒加载无处不在 所有控件都会延时创建
        addChildViewControllers()
        
        setupComposeButton()
    }
    
    override func viewWillAppear(animated: Bool) {
        // 会创建 tabBar中所有控制器对应的按钮
        super.viewWillAppear(animated)
        
        // 将撰写按钮放在最前面
        tabBar.bringSubviewToFront(composeButton)
    }

    // 懒加载
    private lazy var composeButton: UIButton = {
    
        // 自定义button
        let button = UIButton()
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        // 会根据button的背景图片大小调整尺寸
        button.sizeToFit()
        
        return button
    }()
}

// MARK: - 设置页面
extension MainViewController {
    
    /// 添加撰写按钮
    private func setupComposeButton() {
    
        // 1.添加撰写按钮
        tabBar.addSubview(composeButton)
        
        // 2.调整按钮位置
        let count = childViewControllers.count
        // 让按钮宽一点 解决按钮的容认错问题
        let width = tabBar.bounds.width / CGFloat(count) - 1
        composeButton.frame = CGRectInset(tabBar.bounds, 2 * width, 0)
    }
    
    /// 添加所有控制器
    private func addChildViewControllers() {
    
        // 设置tintColor - 图片渲染颜色
        tabBar.tintColor = UIColor.orangeColor()
        
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(HomeTableViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(HomeTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(HomeTableViewController(), title: "我", imageName: "tabbar_profile")
    }
    
    
    private func addChildViewController(vc:UIViewController, title: String, imageName:String) {
    
        // 设置标题
        vc.title = title
        
        // 设置图像
        vc.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
}
